package comment

import (
	"gitee.com/xuxinzhi2206/corehub/database/mysql"
	"gorm.io/gorm"
)

// 评论
type Comment struct {
	gorm.Model
	ObjectId   int64  `gorm:"type:int(11);comment:对象id;"`
	ObjectType int8   `gorm:"type:tinyint(1);comment:对象类型: 1商品 2文章 0未知;"`
	UserId     int64  `gorm:"type:int(11);comment:用户id;"`
	File       string `gorm:"type:text;comment:文件(图片和短视频);"`
	Rating     uint32 `gorm:"type:tinyint(1);comment:评分;"`
	Text       string `gorm:"type:text;comment:评论内容;"`
	Pid        int64  `gorm:"type:int(11);comment:父级评论;"`
	Likes      int64  `gorm:"type:int(11);comment:喜欢;"`
}

// 添加评论
func (c *Comment) CreateComment() (*Comment, error) {
	return c, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Debug().Create(&c).Error
	})
}

// 删除评论
func (c *Comment) DelComment(id int) error {
	return mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Delete("id = ?", id).Error
	})
}

// 根据评论id获取评论
func (c *Comment) GetCommentById(id int) (*Comment, error) {
	return c, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Where("id = ?", id).First(&c).Error
	})
}

// 根据评论id获取评论
func (c *Comment) GetCNumByRating(to [2]int8) (num int64, err error) {
	return num, mysql.WithMysql(func(db *gorm.DB) error {
		switch to {
		case [2]int8{}:
			return db.Model(&c).Count(&num).Find(&c).Error
		}
		return db.Model(&c).Where("rating in(?)", to).Count(&num).Find(&c).Error
	})
}

// 根据对象id批量获取评论
func (c *Comment) GetSubCommentById(id int) (info []*Comment, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Where("object_id = ?", id).Find(&info).Error
	})
}

// 获取评论列表
func (c *Comment) GetCommentList(page, size, objectId int, to [2]int8, objectType int) (data []*Comment, err error) {
	return data, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Where("object_id = ?", objectId).Where("object_type = ?", objectType).Scopes(Paginate(page, size, to)).Find(&data).Error
	})
}

// 根据时间倒序排序
func (c *Comment) DescOrderByTime(page, size, objectId int, to [2]int8, objectType int) (data []*Comment, err error) {
	return data, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Where("object_id = ?", objectId).Where("object_type = ?", objectType).Order("created_at desc").Scopes(Paginate(page, size, to)).Find(&data).Error
	})
}

// 根据时间正序排序
func (c *Comment) AscOrderByTime(page, size, objectId int, to [2]int8, objectType int) (data []*Comment, err error) {
	return data, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Model(&c).Where("object_id = ?", objectId).Where("object_type = ?", objectType).Order("created_at asc").Scopes(Paginate(page, size, to)).Find(&data).Error
	})
}

func Paginate(page, pageSize int, to [2]int8) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		offset := (page - 1) * pageSize
		switch to {
		case [2]int8{}:
			return db.Offset(offset).Limit(pageSize)
		}
		return db.Where("rating in(?)", to).Offset(offset).Limit(pageSize)
	}
}
